package com.industrial.premu.service.impl.sqsj;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.DgQuantityQualityManage;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportHuanbao;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportTongji;
import com.industrial.premu.mapper.DgQuantityQualityManageMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportHuanbaoMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.service.IPreMuImportHuanbaoService;
import com.industrial.premu.service.IPreMuImportLogService;
import com.industrial.premu.util.ValidationUtil;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.ldap.HasControls;


/**
 * 亩产导入数据-生态环境局Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-25
 */
@Service
public class PreMuImportHuanbaoServiceImpl implements IPreMuImportHuanbaoService
{
    @Autowired
    private PreMuImportHuanbaoMapper preMuImportHuanbaoMapper;

    @Autowired
    private DgQuantityQualityManageMapper dgQuantityQualityManageMapper;

    private static final int BATCH_SIZE = 300;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;

    /**
     * 查询亩产导入数据-生态环境局
     *
     * @param id 亩产导入数据-生态环境局主键
     * @return 亩产导入数据-生态环境局
     */
    @Override
    public PreMuImportHuanbao selectPreMuImportHuanbaoById(String id)
    {
        return preMuImportHuanbaoMapper.selectPreMuImportHuanbaoById(id);
    }

    /**
     * 查询亩产导入数据-生态环境局列表
     *
     * @param preMuImportHuanbao 亩产导入数据-生态环境局
     * @return 亩产导入数据-生态环境局
     */
    @Override
    public List<PreMuImportHuanbao> selectPreMuImportHuanbaoList(PreMuImportHuanbao preMuImportHuanbao)
    {
        return preMuImportHuanbaoMapper.selectPreMuImportHuanbaoList(preMuImportHuanbao);
    }

    /**
     * 新增亩产导入数据-生态环境局
     *
     * @param preMuImportHuanbao 亩产导入数据-生态环境局
     * @return 结果
     */
    @Override
    public int insertPreMuImportHuanbao(PreMuImportHuanbao preMuImportHuanbao)
    {
        return preMuImportHuanbaoMapper.insertPreMuImportHuanbao(preMuImportHuanbao);
    }

    /**
     * 修改亩产导入数据-生态环境局
     *
     * @param preMuImportHuanbao 亩产导入数据-生态环境局
     * @return 结果
     */
    @Override
    public int updatePreMuImportHuanbao(PreMuImportHuanbao preMuImportHuanbao)
    {
        return preMuImportHuanbaoMapper.updatePreMuImportHuanbao(preMuImportHuanbao);
    }

    /**
     * 批量删除亩产导入数据-生态环境局
     *
     * @param ids 需要删除的亩产导入数据-生态环境局主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportHuanbaoByIds(String[] ids)
    {
        return preMuImportHuanbaoMapper.deletePreMuImportHuanbaoByIds(ids);
    }

    /**
     * 删除亩产导入数据-生态环境局信息
     *
     * @param id 亩产导入数据-生态环境局主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportHuanbaoById(String id)
    {
        return preMuImportHuanbaoMapper.deletePreMuImportHuanbaoById(id);
    }


    @Override
    public AjaxResult importHuanbaoExcelData(String year, String companyType, MultipartFile file) {
        try{
            ExcelUtil<PreMuImportHuanbao> util = new ExcelUtil<PreMuImportHuanbao>(PreMuImportHuanbao.class);
            List<PreMuImportHuanbao> preMuImportTongjis = util.importExcel(file.getInputStream());
            if (StringUtils.isNull(preMuImportTongjis) || preMuImportTongjis.size() == 0) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","导入数据不能为空");
                return AjaxResult.error("导入失败",resultMap);
            }
            int successNum = 0;
            int failureNum = 0;
            int updateNum = 0;
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            //企业名称为空的错误数据量
            int companyNameBlankCount = 0;
            //值为空的错误量
            int valueErrorCount = 0;
            int valueZeroCount = 0;

            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            StringBuilder allMsg = new StringBuilder();
            List<PreMuImportHuanbao> realList = new ArrayList<PreMuImportHuanbao>();

            //批处理用
            List<String> usccList = new ArrayList<String>();
            List<String> mcImportExistList = new ArrayList<String>();

            List<PreMuImportHuanbao> addImportList = new ArrayList<PreMuImportHuanbao>();
            List<PreMuImportHuanbao> updateImportList = new ArrayList<PreMuImportHuanbao>();

            if (preMuImportTongjis != null && !preMuImportTongjis.isEmpty()) {

                preMuImportTongjis.forEach(data -> {
                    if (data.getUscc() != null && !"".equals(data.getUscc())){
                        usccList.add(data.getUscc().trim());
                        realList.add(data);
                    }
                });

                long count = usccList.stream().distinct().count();
                boolean isRepeat = count < usccList.size();
                if (isRepeat) {
                    Map<String,String> resultMap = new HashMap<>();
                    resultMap.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                    return AjaxResult.error("导入失败",resultMap);
                }

                mcImportExistList = preMuImportHuanbaoMapper.getImportHuanbaoExistList(year, usccList);
                ValidationUtil.validate(realList);
                int travel = 1;
                String numRegx = "^\\d+(\\.\\d+)?$";
                for (int i = 0; i < preMuImportTongjis.size(); i++) {
                    travel++;
                    PreMuImportHuanbao mcImportHuanbaoDO = preMuImportTongjis.get(i);
                    mcImportHuanbaoDO.setYear(year);
                    String uscc = mcImportHuanbaoDO.getUscc();

                    if (uscc == null || "".equals(uscc) || year == null || "".equals(year) || StringUtils.isBlank(mcImportHuanbaoDO.getTotalEquivalent())) {
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、企业 " + mcImportHuanbaoDO.getCompanyName() + " 导入失败：";
                        failureMsg.append(msg + "总排放量不能为空");
                        continue;
                    }else{
                        uscc = uscc.trim();
                        mcImportHuanbaoDO.setUscc(uscc);
                    }

                    if(StringUtils.isBlank(mcImportHuanbaoDO.getCompanyName())){
                        companyNameBlankCount++;
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、企业 " + mcImportHuanbaoDO.getCompanyName() + " 导入失败：";
                        failureMsg.append(msg + "企业名称不能为空");
                        continue;
                    }

                    if(StringUtils.isBlank(mcImportHuanbaoDO.getTotalEquivalent()) || !Pattern.matches(numRegx, mcImportHuanbaoDO.getTotalEquivalent())){
                        valueErrorCount++;
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、企业 " + mcImportHuanbaoDO.getCompanyName() + " 导入失败：";
                        failureMsg.append(msg + "总排放量不是正确小数类型");
                        continue;
                    }

                    BigDecimal totalEquivalentBig = StringUtils.isBlank(mcImportHuanbaoDO.getTotalEquivalent()) ? BigDecimal.ZERO : new BigDecimal(mcImportHuanbaoDO.getTotalEquivalent());
//                    if(totalEquivalentBig.compareTo(BigDecimal.ZERO) < 1){
//                        valueZeroCount++;
//                        failureNum++;
//                        String msg = "<br/>" + failureNum + "、企业 " + mcImportHuanbaoDO.getCompanyName() + " 导入失败：";
//                        failureMsg.append(msg + "总排放量值不能小于等于0");
//                        continue;
//                    }


                    if (mcImportExistList.contains(uscc)) {
                        mcImportHuanbaoDO.setDelFlag("0");
                        mcImportHuanbaoDO.setCompanyType(companyType);
                        updateImportList.add(mcImportHuanbaoDO);
                    } else {
                        mcImportHuanbaoDO.setId(UUID.randomUUID().toString().replace("-", ""));
                        mcImportHuanbaoDO.setDelFlag("0");
                        mcImportHuanbaoDO.setCompanyType(companyType);
                        addImportList.add(mcImportHuanbaoDO);
                    }

                    if (addImportList != null && addImportList.size() >= BATCH_SIZE) {
                        int importNum = preMuImportHuanbaoMapper.batchSave(addImportList);
                        successNum += importNum;
                        addImportList.clear();
                    }

                    if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {
                        int importNum = preMuImportHuanbaoMapper.batchUpdateByUscc(year, updateImportList);
                        successNum += importNum;
                        updateNum += importNum;
                        updateImportList.clear();
                    }
                }

                if (addImportList != null && !addImportList.isEmpty()) {
                    int importNum = preMuImportHuanbaoMapper.batchSave(addImportList);
                    successNum += importNum;
                    addImportList.clear();
                }

                if (updateImportList != null && !updateImportList.isEmpty()) {
                    int importNum = preMuImportHuanbaoMapper.batchUpdateByUscc(year, updateImportList);
                    successNum += importNum;
                    updateNum += importNum;
                    updateImportList.clear();
                }

                if (successNum > 0) {
                    allMsg.insert(0, "恭喜您，共" + successNum + " 条数据导入成功！");
                }

                if(failureNum > 0){
                    allMsg.insert(0, "<br/>很抱歉，错误如下：" + failureMsg.toString());
                }

                //企业名称为空的数量
                if(companyNameBlankCount > 0){
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("企业名称不能为空");
                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());

                        String failCount = dgQuantityQualityManage.getFailCount();
                        Integer oldFailCount = Integer.parseInt(failCount);

                        dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount + oldFailCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }else{
                        comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                        comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setFailCount(String.valueOf(companyNameBlankCount));
                        comapnNameBlankParams.setRuleType("1");
                        dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                    }
                }else{
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("企业名称不能为空");
                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                        dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }
                }

                //值小于等于0
                if(valueZeroCount > 0){
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("值小于0的错误");

                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                        dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }else{
                        comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                        comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setFailCount(String.valueOf(valueZeroCount));
                        comapnNameBlankParams.setRuleType("1");
                        dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                    }
                }else{
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("值小于0的错误");
                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                        dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }
                }
                //值存在错误的情况
                if(valueErrorCount > 0){
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("值不存在或者是格式有误");

                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                        dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }else{
                        comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                        comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                        comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                        comapnNameBlankParams.setFailCount(String.valueOf(valueErrorCount));
                        comapnNameBlankParams.setRuleType("1");
                        dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                    }
                }else{
                    DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                    comapnNameBlankParams.setSource("环保局");
                    comapnNameBlankParams.setYears(year);
                    comapnNameBlankParams.setProvince(sysUser.getProvince());
                    comapnNameBlankParams.setCity(sysUser.getCity());
                    comapnNameBlankParams.setCounty(sysUser.getDistrict());
                    comapnNameBlankParams.setRuleName("值不存在或者是格式有误");
                    List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                    if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                        DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                        dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                        dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                        dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                        dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                    }
                }


                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("msg","导入成功");
                resultMap.put("sum",String.valueOf(successNum));
                resultMap.put("updateNum",String.valueOf(updateNum));
                resultMap.put("failureNum",String.valueOf(failureNum));
                resultMap.put("allMsg",allMsg.toString());
                return AjaxResult.success(resultMap);
            }
        }catch (Exception e){
            String requestURI = "/industrial-premu/importExcelData";
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            e.printStackTrace();
            return AjaxResult.warn("导入失败");
        }
        return AjaxResult.warn("导入失败");
    }
    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult removeData(PreMuImportHuanbao params,String deptCode) {
        preMuImportHuanbaoMapper.removeData(params);
        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(String.valueOf(params.getYear()));
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
        return AjaxResult.success();
    }
}